﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Telerik.Web.Mvc;
using ThuySan.Bussiness;
using ThuySan.Models;

namespace ThuySan.Areas.Backend.Controllers
{
    [Authorize]
    public class EmailController : Controller
    {
        private readonly UnitOfWork _unitOfWork = new UnitOfWork();

        public ActionResult Index()
        {
            return View();
        }

        [GridAction]
        public ActionResult GetList()
        {
            return View(new GridModel(_unitOfWork.EmailTemplateRepository.Select().Select(c => new
            {
                c.Id,
                c.Name
            })));
        }

        public ActionResult Edit(string id)
        {
            int guid;
            if (int.TryParse(id, out guid))
            {
                EmailTemplateModel emailTemplate = _unitOfWork.EmailTemplateRepository.SelectbyId(guid);
                if (emailTemplate != null)
                {
                    EmailTemplateModel templateModelModel = emailTemplate;
                    return View(templateModelModel);
                }
            }
            return RedirectToAction("Index");
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Edit(EmailTemplateModel emailTemplateModel)
        {
            if (ModelState.IsValid)
            {
                EmailTemplate emailTemplate = _unitOfWork.EmailTemplateRepository.SelectbyId(emailTemplateModel.Id);
                emailTemplateModel.Update(emailTemplate);
                if (_unitOfWork.EmailTemplateRepository.CheckUpdateEmailTemplate(emailTemplate))
                {
                    Exception exception;
                    _unitOfWork.EmailTemplateRepository.Update(emailTemplate, out exception);
                    if (exception == null)
                    {
                        return RedirectToAction("Index");
                    }
                }
            }
            return View(emailTemplateModel);
        }
    }
}
